<template>
  <el-drawer :title="!dataForm.id ? '新建' : '办结'" :visible.sync="visible"
             :wrapperClosable="false" size="1000px" append-to-body
             class="JNPF-common-drawer">
    <div class="JNPF-flex-main">
      <div class="dynamicForm ">
        <el-form ref="elForm" :model="dataForm" :rules="rules" size="small" label-width="100px" label-position="right" >
          <template v-if="!loading">
            <el-col   :span="24" >
              <el-card class="mb-20" shadow ="always"  header ="办结">
                <el-col :span="8"  >
                  <el-form-item  label="维修人"
                                 prop="maintenanceUser" >
                    <el-select   v-model="dataForm.maintenanceUser"
                                 placeholder="请选择"  clearable  :style='{"width":"100%"}'>
                      <el-option v-for="(item, index) in maintenanceUserOptions" :key="index" :label="item.fullName" :value="item.id" :disabled="item.disabled" ></el-option>

                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col :span="8"  >
                  <el-form-item  label="到场时间"
                                 prop="startTime" >
                    <el-date-picker   v-model="dataForm.startTime"
                                      placeholder="请选择"  clearable  :style='{"width":"100%"}' type="datetime"  format="yyyy-MM-dd hh:mm:ss"  value-format="timestamp" >

                    </el-date-picker>
                  </el-form-item>
                </el-col>
                <el-col :span="8"  >
                  <el-form-item  label="离开时间"
                                 prop="endTime" >
                    <el-date-picker   v-model="dataForm.endTime"
                                      placeholder="请选择"  clearable  :style='{"width":"100%"}' type="datetime"  format="yyyy-MM-dd hh:mm:ss"  value-format="timestamp" >

                    </el-date-picker>
                  </el-form-item>
                </el-col>
                <el-col :span="12"  >
                  <el-form-item  label="处理内容"
                                 prop="handlingContent" >
                    <el-input   v-model="dataForm.handlingContent"
                                placeholder="请输入"  :style='{"width":"100%"}' true  type="textarea"  :autosize='{"minRows":4,"maxRows":4}' >

                    </el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="10"  >
                  <el-form-item  label="处理文件"
                                 prop="handlingFile" >
                    <JNPF-UploadFz   v-model="dataForm.handlingFile"
                                     :fileSize="10"    sizeUnit="MB"  :limit="9"  buttonText="点击上传" >

                    </JNPF-UploadFz>
                  </el-form-item>
                </el-col>
              </el-card>
            </el-col>
            <el-col :span="24">
              <el-row :gutter="15">
                <el-col :span="24"  >
                  <el-form-item label-width="0">
                    <div class="JNPF-common-title">
                      <h2>物品详情</h2>
                    </div>
                    <el-table :data="dataForm.zcglpropertyrepairitemList" size='mini'   show-summary :summary-method="getzcgl_property_repair_itemSummaries"  >
                      <el-table-column type="index" width="50" label="序号" align="center" />
                      <el-table-column prop="thingName" label="物品名称" >
                        <template slot-scope="scope">
                          <el-input   v-model="scope.row.thingName"
                                      placeholder="请输入"  clearable  :style='{"width":"100%"}'>
                          </el-input>
                        </template>
                      </el-table-column>
                      <el-table-column prop="thingPrice" label="物品价格" >
                        <template slot-scope="scope">
                          <el-input    @input="toJs(scope.row)"  v-model="scope.row.thingPrice"
                                      placeholder="请输入"  clearable  :style='{"width":"100%"}'>
                          </el-input>
                        </template>
                      </el-table-column>
                      <el-table-column prop="thingCount" label="物品数量" >
                        <template slot-scope="scope">
                          <el-input   @input="toJs(scope.row)"  v-model="scope.row.thingCount"
                                      placeholder="请输入"  clearable  :style='{"width":"100%"}'>
                          </el-input>
                        </template>
                      </el-table-column>
                      <el-table-column prop="total" label="总金额" >
                        <template slot-scope="scope">
                          <el-input  disabled  v-model="scope.row.total"
                                      placeholder="请输入"  clearable  :style='{"width":"100%"}'>
                          </el-input>
                        </template>
                      </el-table-column>

                      <el-table-column prop="thingType" label="物品类型" >
                        <template slot-scope="scope">
                          <el-input   v-model="scope.row.thingType"
                                      placeholder="请输入"  clearable  :style='{"width":"100%"}'>
                          </el-input>
                        </template>
                      </el-table-column>
                      <el-table-column label="操作" width="50" >
                        <template slot-scope="scope">
                          <el-button size="mini" type="text" class="JNPF-table-delBtn" @click="delzcglpropertyrepairitemList(scope.$index)">删除</el-button>
                        </template>
                      </el-table-column>
                    </el-table>
                    <div class="table-actions" @click="addzcglpropertyrepairitemList()">
                      <el-button type="text" icon="el-icon-plus">添加</el-button>
                    </div>
                  </el-form-item>
                </el-col>
              </el-row>
            </el-col>
          </template>
        </el-form>
        <SelectDialog v-if="selectDialogVisible" :config="currTableConf" :formData="dataForm"
                      ref="selectDialog" @select="addForSelect" @close="selectDialogVisible=false"/>
      </div>
      <div class="drawer-footer">
        <el-button @click="visible = false"> 取 消</el-button>
        <el-button type="primary" @click="dataFormSubmit()" :loading="btnLoading"> 确 定</el-button>
      </div>






    </div>
  </el-drawer>
</template>
<script>
import request from '@/utils/request'
import { getDataInterfaceRes } from '@/api/systemData/dataInterface'
import { getDictionaryDataSelector } from '@/api/systemData/dictionary'

export default {
  components: {},
  props: [],
  data() {
    return {

      visible: false,
      loading: false,
      btnLoading: false,
      selectDialogVisible: false,
      currTableConf:{},
      addTableConf:{
        zcglpropertyrepairitemList :{"popupType":"dialog","hasPage":true,"popupTitle":"选择数据","pageSize":20,"columnOptions":[],"interfaceId":"","interfaceName":"","relationOptions":[],"templateJson":[],"popupWidth":"800px"},
      },
      tableRows:{
        zcglpropertyrepairitemList:{
          thingName : '',
          thingPrice : '',
          thingCount : '',
          thingType : '',
          enabledmark:undefined
        },
      },
      currVmodel:"",
      dataForm: {
        maintenanceUser : "",
        startTime : '',
        endTime : '',
        handlingContent : '',
        handlingFile : [],
        zcglpropertyrepairitemList:[],
      },
      rules:
        {
          maintenanceUser: [
            {
              required: true,
              message: '请选择',
              trigger: 'change'
            },
          ],
          startTime: [
            {
              required: true,
              message: '请选择',
              trigger: 'change'
            },
          ],
          endTime: [
            {
              required: true,
              message: '请选择',
              trigger: 'change'
            },
          ],
          handlingContent: [
            {
              required: true,
              message: '请输入',
              trigger: 'blur'
            },
          ],



        },
      maintenanceUserOptions:[{"fullName":"选项一","id":"1"},{"fullName":"选项二","id":"2"}],

    }
  },
  computed: {},
  watch: {},
  created() {
  },
  mounted() {},
  methods: {
    toJs(value){
    value.total = value.thingPrice*value.thingCount

    },

    zcgl_property_repair_itemExist() {
      let isOk = true;
      for(let i=0;i<this.dataForm.zcglpropertyrepairitemList.length;i++){
        const e = this.dataForm.zcglpropertyrepairitemList[i];
      }
      return isOk;
    },
    getzcgl_property_repair_itemSummaries(param) {
      const summaryField = ["thingCount","total"];
      const { columns, data } = param;
      const sums = [];
      columns.forEach((column, index) => {
        if (index === 0) {
          sums[index] = '合计';
          return;
        }
        if (!summaryField.includes(column.property)) {
          sums[index] = '';
          return;
        }
        const values = data.map(item => Number(item[column.property]));
        if (!values.every(value => isNaN(value))) {
          sums[index] = values.reduce((prev, curr) => {
            const value = Number(curr);
            if (!isNaN(value)) {
              return prev + curr;
            } else {
              return prev;
            }
          }, 0);
        } else {
          sums[index] = '';
        }
      });
      return sums;
    },
    clearData(){
      this.dataForm.maintenanceUser = "";
      this.dataForm.startTime = '';
      this.dataForm.endTime = '';
      this.dataForm.handlingContent = '';
      this.dataForm.handlingFile = [];
      this.dataForm.zcglpropertyrepairitemList=[];
    },
    init(id) {
      this.dataForm.id = id || 0;
      this.visible = true;
      this.$nextTick(() => {
        this.$refs['elForm'].resetFields();
        if(this.dataForm.id){
          this.loading = true
          request({
            url: '/api/property/repair/detail/' + this.dataForm.id,
            method: 'get'
          }).then(res => {
            this.dataInfo(res.data)
            this.loading = false
          });
        }else{
          this.clearData()
        }
      });
      this.$store.commit('generator/UPDATE_RELATION_DATA', {})
    },
    // 表单提交
    dataFormSubmit() {
      this.$refs['elForm'].validate((valid) => {
        if (valid) {
          if (!this.zcgl_property_repair_itemExist()) return
          this.request()
        }
      })
    },
    request() {
      this.btnLoading = true
      let _data =this.dataList()
      if (!this.dataForm.id) {
        request({
          url: '/api/system/Zcgl_property_repair',
          method: 'post',
          data: _data
        }).then((res) => {
          this.$message({
            message: res.msg,
            type: 'success',
            duration: 1000,
            onClose: () => {
              this.visible = false
              this.btnLoading = false
              this.$emit('refresh', true)
            }
          })
        }).catch(()=>{  this.btnLoading = false  })
      }else{
        request({
          url: '/api/property/repair/'+this.dataForm.id,
          method: 'PUT',
          data: _data
        }).then((res) => {
          this.$message({
            message: res.msg,
            type: 'success',
            duration: 1000,
            onClose: () => {
              this.visible = false
              this.btnLoading = false
              this.$emit('refresh', true)
            }
          })
        }).catch(()=>{  this.btnLoading = false  })
      }
    },
    addzcglpropertyrepairitemList(){
      let item = {
        thingName:undefined,
        thingPrice:undefined,
        thingCount:undefined,
        thingType:undefined,
      }
      this.dataForm.zcglpropertyrepairitemList.push(item)
    },
    delzcglpropertyrepairitemList(index) {
      this.dataForm.zcglpropertyrepairitemList.splice(index, 1);
    },
    openSelectDialog(key) {
      this.currTableConf=this.addTableConf[key]
      this.currVmodel=key
      this.selectDialogVisible = true
      this.$nextTick(() => {
        this.$refs.selectDialog.init()
      })
    },
    addForSelect(data) {
      for (let i = 0; i < data.length; i++) {
        let item={...this.tableRows[this.currVmodel],...data[i]}
        this.dataForm[this.currVmodel].push(item)
      }
    },
    dataList(){
      var _data = JSON.parse(JSON.stringify(this.dataForm));
      _data.handlingFile = Array.isArray(_data.handlingFile)? JSON.stringify(_data.handlingFile):'[]'
      for(let i=0;i<_data.zcglpropertyrepairitemList.length;i++){
        var _list = _data.zcglpropertyrepairitemList[i];
      }
      return _data;
    },
    dataInfo(dataAll){
      let _dataAll =dataAll
      _dataAll.handlingFile = _dataAll.handlingFile ?JSON.parse(_dataAll.handlingFile):[]
      for(let i=0;i<_dataAll.zcglpropertyrepairitemList.length;i++){
        var _list = _dataAll.zcglpropertyrepairitemList[i];
        _list.total = _list.thingCount*_list.thingPrice

      }
      this.dataForm = _dataAll
    },
  },
}

</script>
